package com.abigdreamer.im.server.module;

import com.abigdreamer.im.server.log.EIMLogger;
import com.abigdreamer.im.server.serverConfig.EIMServerConfig;
import com.abigdreamer.im.server.serverConfig.ServerConfigFactory;

/**
 * IM的服务器类（简单实现版） 注意：此类必须是单例模式 包含 1: 服务器的配置信息 2：服务器缓存对象（ServerCache） 3：三种Socket
 * 
 * 启动时所需完成的步骤 1：初始化缓存对象 2：初始化服务器数据对象 3：启动服务，在某个端口处监听
 */
public class EIMServer {

	private static EIMServer instance;
	/** 服务器化缓存对象 */
	private ServerCache cache;
	/** 聊天消息 ServerSocket */
	private EIMChatSocket chatSocket;
	/** 文件消息 ServerSocket */
	private EIMFileSocket fileSocket;
	/** 服务器的配置信息 */
	private EIMServerConfig config;
	/** 服务器启动的标志 */
	private boolean isStart = false;

	public static EIMServer getInstance() {
		if (instance == null) {
			instance = new EIMServer();
		}
		return instance;
	}

	private EIMServer() {
		initServer();
		isStart = false;
	}

	private void initServer() {
		EIMLogger.INFO("初始化服务器信息");
		config = ServerConfigFactory.createConfig(EIMServerConfig.class);
		cache = ServerCache.getInstance();
		chatSocket = new EIMChatSocket(config.getChatSocketConfig());
		fileSocket = new EIMFileSocket(config.getFileSocketConfig());
	}

	public boolean startServer() {
		boolean sucess = false;
		if (false == isStart) {
			chatSocket.startSocket();
			fileSocket.startSocket();
			isStart = true;
			sucess = true;
			EIMLogger.INFO("成功启动服务器");
		} else {
			EIMLogger.INFO("服务器已经启动了，无需再启动");
			sucess = false;
		}
		return sucess;
	}

	public boolean closeServer() {
		boolean sucess = false;
		if (true == isStart) {
			chatSocket.closeSocket();
			fileSocket.closeSocket();
			isStart = false;
			sucess = true;
			EIMLogger.INFO("成功关闭服务器");
		} else {
			EIMLogger.INFO("服务器已经关闭了，无需再关闭");
			sucess = false;
		}
		return sucess;
	}

	public boolean refreshServer() {
		boolean sucess = false;
		if (true == isStart) {
			closeServer();
			initServer();
			startServer();
			sucess = true;
			EIMLogger.INFO("成功刷新服务器");
		} else {
			EIMLogger.INFO("服务器没启动，不能刷新");
			sucess = false;
		}
		return sucess;
	}

	public ServerCache getCache() {
		return cache;
	}

	public void setCache(ServerCache cache) {
		this.cache = cache;
	}

	public EIMChatSocket getChatSocket() {
		return chatSocket;
	}

	public void setChatSocket(EIMChatSocket chatSocket) {
		this.chatSocket = chatSocket;
	}

	public EIMFileSocket getFileSocket() {
		return fileSocket;
	}

	public void setFileSocket(EIMFileSocket fileSocket) {
		this.fileSocket = fileSocket;
	}

	public boolean isStart() {
		return isStart;
	}

	public void setStart(boolean isStart) {
		this.isStart = isStart;
	}

	public static void setInstance(EIMServer instance) {
		EIMServer.instance = instance;
	}

	public EIMServerConfig getConfig() {
		return config;
	}

	public void setConfig(EIMServerConfig config) {
		this.config = config;
	}

}
